/* $RCSFile: UploadFlash.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/FlashModule/UploadFlash.aspx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:20  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:54  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.Settings;
using AddonNice.Security;
using AddonNice.UI;
using AddonNice.Helpers;
using AddonNice.Diagnostics;
using AddonNice.UI.WebControls;
using AddonNice.Configuration;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.FlashModule
{
	
	public partial class UploadFlash : AddEditItemPage
	{
		// Configuration
		private bool	_uploadIsEnabled			=	true;
		private string	_imageFolder				=	string.Empty;
		private string _returnPath					=	string.Empty;

		// Messages
		private string	_noFileMessage				=	LocalizeHelper.Localize("NO_FILE_MESSAGE","No File");
		private string	_uploadSuccessMessage		=	LocalizeHelper.Localize("UPLOAD_SUCCESS_MESSAGE","Succes");
		private string	_noImagesMessage			=	LocalizeHelper.Localize("NO_IMAGE_MESSAGE","No Image");
		private string  _noFolderSpecifiedMessage	=	LocalizeHelper.Localize("NO_FOLDER_SPECIFIED_MESSAGE","Bad folder");

        public UploadFlash()
            : base(false, true, true, false)
        { }

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void Page_Load(object sender, System.EventArgs e)
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UploadFlash Page_Load BEG IsPostBack: {0}.", IsPostBack),PageTraceSwitch.Sw.Info);
			// Form the script that will update the INPUT for file upload when a file is selected.
			String scriptString = "function UpdateOpener(filename) {opener.document.all['" + Request.QueryString["FieldID"] + "'].value = filename; closeWindow();}";
			scriptString += "function closeWindow() {opener.focus(); self.close();}";
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UploadFlash Page_Load scriptString: {0}.", scriptString),PageTraceSwitch.Sw.Info);
			Type cs	=	GetType();
			if( !((ADNPage)this).IsPageClientScriptBlockRegistered(cs,"UpdateOpener"))
				((ADNPage)this).RegisterPageClientScriptBlock(cs,"UpdateOpener", scriptString,true);

			uploadpanel.Visible =   _uploadIsEnabled;
	    
			_imageFolder        =   moduleSettingsDic[flStr.FlashPath].FullPath;
            if ( PageTraceSwitch.Sw.TraceVerbose )
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UploadFlash Page_Load _imageFolder: {0}.", _imageFolder),PageTraceSwitch.Sw.Info);

			if (Helpers.IOHelper.CreateDirectory(Server.MapPath(_imageFolder)))
				DisplayImages();
			else
				uploadmessage.Text=_noFolderSpecifiedMessage;
            if ( PageTraceSwitch.Sw.TraceVerbose )
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UploadFlash Page_Load END IsPostBack: {0}.", IsPostBack),PageTraceSwitch.Sw.Info);
		}

		/// <summary>
		/// Set the module guids with free access to this page
		/// </summary>
		protected override ArrayList AllowedModules
		{
			get
			{
				ArrayList al = new ArrayList();
				al.Add ("623EC4DD-BA40-421c-887D-D774ED8EBF02");
				return al;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void uploadButton_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			if (Helpers.IOHelper.CreateDirectory(Server.MapPath(_imageFolder)))
			{
				if (uploadfile.PostedFile.FileName != string.Empty)
				{
					if (PageTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]UploadFlash uploadButton_Command uploadfile.PostedFile.FileName: {0}.",uploadfile.PostedFile.FileName),PageTraceSwitch.Sw.Info);
					string virtualPath		=	string.Empty;
					string physicalPath		=	string.Empty;
					try
					{
						virtualPath				=	_imageFolder + "/" + System.IO.Path.GetFileName( uploadfile.PostedFile.FileName);
						physicalPath			=	Server.MapPath(virtualPath);
						uploadfile.PostedFile.SaveAs(physicalPath);
						uploadmessage.Text		=	_uploadSuccessMessage;
					}
					catch(Exception exe)
					{
						if (PageTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]UploadFlash uploadButton_Command virtualPath: {0}, physicalPath: {1}, exe: {2}.",virtualPath,physicalPath,exe),PageTraceSwitch.Sw.Info);
						uploadmessage.Text ="Error"; 
					}
				}
				else
				{
					if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine("[V]UploadFlash uploadButton_Command no FileName.",PageTraceSwitch.Sw.Info);
					uploadmessage.Text = ("_noFileMessage");
				}
			}
			else
			{
				if (PageTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]UploadFlash uploadButton_Command no access or inexisting _imageFolder: {0}.",_imageFolder),PageTraceSwitch.Sw.Info);
				uploadmessage.Text = _noFolderSpecifiedMessage;
			}
			DisplayImages();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		public void Delete_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			if (_imageFolder != string.Empty)
			{
				try
				{
					System.IO.File.Delete(Server.MapPath(_imageFolder) + @"\" + e.CommandArgument);
				}
				catch (Exception ex)
				{
					if (PageTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"UploadFlash Delete_Command e.CommandArgument: {0}, ex: {1}.", e.CommandArgument, ex),PageTraceSwitch.Sw.Info);
				}
				DisplayImages();
			}
		}

		/// <summary>
		/// ReturnFolderContentArray
		/// </summary>
		/// <returns></returns>
		private string[] ReturnFolderContentArray()
		{
			if (_imageFolder != string.Empty)
			{
				string gallerytargetpath		=	string.Empty;
				try
				{
					gallerytargetpath			=	Server.MapPath(_imageFolder);
					string[] galleryfolderarray =	Helpers.IOHelper.GetFiles(gallerytargetpath,"*.swf");
					return galleryfolderarray;
				}
				catch(Exception ex)
				{
					if (PageTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]UploadFlash ReturnFolderContentArray gallerytargetpath: {0}, ex: {1}.",gallerytargetpath, ex),PageTraceSwitch.Sw.Info);
					return null;
				}
			}
			else
			{
				return null;
			}

		}
    
		/// <summary>
		/// DisplayImages
		/// </summary>
		public void DisplayImages()
		{
			_returnPath                             =  moduleSettingsDic[flStr.FlashPath].FullPath;

			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UploadFlash DisplayImages _returnPath: {0}", _returnPath),PageTraceSwitch.Sw.Info);
			
			string[] galleryfolderarray				=	ReturnFolderContentArray();
			flashTable.Controls.Clear();
			if ( galleryfolderarray == null || galleryfolderarray.GetLength(0) == 0 )
			{
				gallerymessage.Text					=	_noImagesMessage;
			}
			else
			{
				string galleryfilename				=	string.Empty;
        
				gallerymessage.Text					=	string.Empty;
				foreach (string galleryfolderarrayitem in galleryfolderarray)
				{ 
					galleryfilename					=	galleryfolderarrayitem.ToString();
					galleryfilename					=	galleryfilename.Substring(galleryfilename.LastIndexOf(@"\")+1);
					if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UploadFlash DisplayImages galleryfilename: {0}", galleryfilename),PageTraceSwitch.Sw.Info);
      
					AddonNice.UI.WebControls.FlashMovie flashMovie = new AddonNice.UI.WebControls.FlashMovie();							
					flashMovie.MovieName			=	_imageFolder + "/" + galleryfilename ;
					flashMovie.MovieHeight			=	"150px";
					flashMovie.MovieWidth			=	"150px";

					Label filenameLbl= new System.Web.UI.WebControls.Label();
					filenameLbl.Text				=	galleryfilename;
					System.Web.UI.WebControls.HyperLink selectCmd= new System.Web.UI.WebControls.HyperLink();
					selectCmd.Text					=	LocalizeHelper.Localize("SELECT","Select");
					selectCmd.CssClass				=	"CommandButton";
					selectCmd.NavigateUrl="javascript:UpdateOpener('"+_returnPath + "/" + galleryfilename +"')";

					LinkButton deleteCmd= new System.Web.UI.WebControls.LinkButton();
					deleteCmd.Text					=	LocalizeHelper.Localize("DELETE","Delete");
					deleteCmd.CommandName			=	"DELETE";
					deleteCmd.CssClass				=	"CommandButton";
					deleteCmd.CommandArgument		=	galleryfilename;
					deleteCmd.Command				+=	new System.Web.UI.WebControls.CommandEventHandler(Delete_Command);

					TableRow rowItem				=	new TableRow();       
         
					TableCell cellItemImage			=	new TableCell();
					TableCell cellItemSelect		=	new TableCell();
					TableCell cellItemDelete		=	new TableCell();
					TableCell cellItemFileName		=	new TableCell();
					cellItemImage.Controls.Add(flashMovie);
					cellItemFileName.Controls.Add(filenameLbl);
					cellItemSelect.Controls.Add(selectCmd);
					cellItemDelete.Controls.Add(deleteCmd);
          
           
					rowItem.Controls.Add(cellItemImage);
					rowItem.Controls.Add(cellItemFileName);
					rowItem.Controls.Add(cellItemSelect);
					rowItem.Controls.Add(cellItemDelete);
               
					flashTable.Controls.Add(rowItem);
				}
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
           ((ImageButton)saveAndCloseButton).OnClientClick = "closeWindow();return false;";
           ((ImageButton)saveAndCloseButton2).OnClientClick = "closeWindow();return false;";
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]UploadFlash InitializeComponent Begin",PageTraceSwitch.Sw.Info);
			uploadButton.Command    += new CommandEventHandler(this.uploadButton_Command);
			Load                    += new EventHandler(Page_Load);
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]UploadFlash InitializeComponent End",PageTraceSwitch.Sw.Info);
		}

		#endregion 
	}
}
